package com.kt.appinfo.contorller;

import com.kt.appinfo.pojo.DevUser;
import com.kt.appinfo.servlet.devServlet;
import com.kt.appinfo.tools.Constants;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/dev")
@Log4j2
public class Contorller {
    @Autowired
    private devServlet devServlet;

    /**
     * 从首页跳转到开发者登录 页面
     *
     * @param
     * @return
     * @Author zhuzhuhong
     * @Date 2019/10/22
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        return "devlogin";
    }

    /**
     * 执行登录
     *
     * @param devCode
     * @param devPassword
     * @return
     * @Author zhuzhuhong
     * @Date 2019/10/22
     */
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public String doLogin(@RequestParam("devCode") String devCode,
                          @RequestParam("devPassword") String devPassword,
                          Model model,HttpSession session,
                          HttpServletRequest request) {
        try {
            DevUser devUser = devServlet.doLogin(devCode, devPassword);
            if (devUser == null) {
                request.setAttribute("error", "用户名或密码错误");
                return "redirect:login";
            } else {
                //登录 成功，将开发者信息放入session,同时跳转main页面
//                request.getSession().setAttribute("devUser", devCode);
                     session.setAttribute(Constants.DEV_USER_SESSION,devUser);
                return "developer/main";
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            model.addAttribute("error", "后台接口出现异常");
            return "redirect:../../403";
        }

    }

    @RequestMapping(value = "/flatfrom/main")
    public String main(HttpSession session) {
        if (session.getAttribute(Constants.DEV_USER_SESSION) == null) {
            return "redirect:/dev/login";
        }
        return "redirect:/dev/main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.DEV_USER_SESSION);
        return "devlogin";
    }
}
